package benny.ApkposStore.Activity;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import benny.ApkposStore.R;
import benny.ApkposStore.R.string;
import benny.ApkposStore.utils.ApkConstant;
import benny.ApkposStore.utils.ApkUntils;
import benny.ApkposStore.utils.Apkglobal;
import benny.ApkposStore.utils.NetUtils;

public class RegisterActivity extends Activity {

	private Button registerButton;
	private Button closeButton;
	private EditText usertext;
	private EditText pwdtext;
	private EditText shoptext;
	private EditText cdkeytext;
	private EditText companytext;
	private String cdkeystr="";
	private String tag = "RegisterActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		ApkUntils.fullscreen(this);
		setContentView(R.layout.registerview);
		registerButton = (Button) findViewById(R.id.register);
		closeButton = (Button) findViewById(R.id.close);
		usertext = (EditText) findViewById(R.id.usernametext);
		pwdtext = (EditText) findViewById(R.id.pwdtext);
		companytext = (EditText) findViewById(R.id.companytext);
		shoptext = (EditText) findViewById(R.id.shoptext);
		cdkeytext = (EditText) findViewById(R.id.cdkeytext);
		registerButton.setOnClickListener(new registerListener());
		closeButton.setOnClickListener(new closeListener());
		
	}
	
	
	//异步激活CDKEY任务
		private class AsyncCdkey extends AsyncTask<Void, Void, Integer> {
			private String mCdKey = "";
			private String mUUID = "";
			private String mUserName = "";
			private String mPwd = "";
			private String msg = "激活失败，请重新尝试！";
		    private ProgressDialog progressDialog = null;
			private String mCompany_id="";
			private String mShop_id="";

			public void setCdKey(String cdKey) {
				mCdKey = ApkUntils.escape(cdKey);
			}
			
			public void setUUID(String uuid) {
				mUUID = ApkUntils.escape(uuid);
			}
			
			public void setUersName(String username) {
				mUserName = ApkUntils.escape(username);
			}
			
			public void setPwd(String pwd) {
				mPwd = ApkUntils.escape(pwd);
			}
			public void setCompany_id(String company_id) {
				mCompany_id = ApkUntils.escape(company_id);
			}
			public void setShop_id(String shop_id) {
				mShop_id = ApkUntils.escape(shop_id);
			}
			
			private void dialog1(AlertDialog.Builder builder, String msg,
					int dialogTitle1, Integer icon) {
		        builder.setMessage(msg);
				builder.setTitle(dialogTitle1);
				builder.setIcon(icon);
				builder.setNegativeButton("关闭",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}

						});
			
				builder.create().show();

			}
			@Override
			protected Integer doInBackground(Void... params) {
				String url = ApkConstant.BaseCDkeyUrl;
				try {
					
					
					String postParams = "type=0&"
							+ "cdkey=" + mCdKey + "&"
							+ "uuid=" + mUUID + "&"
							+ "company_id=" + mCompany_id + "&"
							+ "shop_id=" + mShop_id + "&"
							+ "username=" + mUserName + "&"
							+ "pwd=" + mPwd;
					String data = NetUtils.fetchTextFromPost(url, postParams);
				
					JSONObject jsonObj = new JSONObject(data);
					if(jsonObj.getInt("ret") != 0) {
						Log.e(tag, "AsyncCdkey: login failed:" + jsonObj.getString("msg"));
						msg="激活失败！"+jsonObj.getString("msg");
						return -1;
					}
							
					return 0;				
				}
				catch(Exception e) {
					Log.e(tag, "AsyncCdkey:" + e.getMessage());
					msg=e.getMessage();
				}
				
				
				return -1;
			}
			
			//在doInBackground前执行
			protected void onPreExecute () {
				//TODO: 显示正在登陆的提示
				
				//progressDialog = ProgressDialog.show(ApkposStoreActivity.this, "请稍等...", "正在登陆中...", true);
				progressDialog = new ProgressDialog(RegisterActivity.this);
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progressDialog.setIcon(R.drawable.apkn);  
				progressDialog.setTitle("请稍等...");
				progressDialog.setMessage("正在连接网络激活...");   
				progressDialog.setCancelable(true);  
				progressDialog.show();
			}
			
			//在doInBackground后执行
			protected void onPostExecute(Integer result) {
				progressDialog.dismiss();
				if(result == 0) {
					// ok
					
					 try {
							ApkUntils.WriteSharedPreferences(RegisterActivity.this, 
									"CDKEY", "cdkey", cdkeystr);
							Apkglobal.setcdkey(cdkeystr);
						} catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							return ;
						}
					 Toast.makeText(getApplicationContext(), "激活成功！", Toast.LENGTH_LONG)
						.show(); // 显示提示
					 
             		Intent intent = new Intent();
         			intent.setClass(RegisterActivity.this, ApkposStoreActivity.class);
         			startActivity(intent);
         			ApkUntils.openActivityAnim(RegisterActivity.this,10);
         			finish(); 	
				}
				else if(result == -1) {
				//TODO: login failed，取消正在激活的提示，换成提示激活失败
					Builder builderdd = new Builder(RegisterActivity.this);
					dialog1(builderdd,msg, string.dialog_title1,
							android.R.drawable.ic_dialog_info);	
				}
			}		
		}
		

		
	class registerListener implements OnClickListener {

		

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String resultString = "";
           if (usertext.length()==0) {
        	   resultString="账号名称不能为空！";
		   }
           else if (pwdtext.length()==0) {
        	   resultString="账号密码不能为空！";
		   }
           else if (companytext.length()==0){
        	   resultString="公司编号不能为空！";
           }
           else if (shoptext.length()==0) {
        	   resultString="商铺编号不能为空!";
           }
           else if (cdkeytext.length()==0) {
        	   resultString="CDKEY不能为空！";
           }
           
           if (resultString.length()>0) {
       		Toast.makeText(getApplicationContext(), resultString,
					Toast.LENGTH_LONG).show();
       		return;
		  }
            cdkeystr=cdkeytext.getText().toString();
			AsyncCdkey asyncCdkey = new AsyncCdkey();
			asyncCdkey.setCdKey(cdkeystr);
			asyncCdkey.setUUID(Apkglobal.getuuid());
			asyncCdkey.setUersName(usertext.getText().toString());
			asyncCdkey.setPwd(pwdtext.getText().toString());	
			asyncCdkey.setCompany_id(companytext.getText().toString());	
			asyncCdkey.setShop_id(shoptext.getText().toString());	
			asyncCdkey.execute();
			  
		}

	}
	class closeListener implements OnClickListener {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ApkUntils.quit(RegisterActivity.this);
		}
		
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		System.gc(); // 回收系统资源
		super.onDestroy();
	}

}
